package com.xindaoapp.happypet.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.XDHttpClient;
import com.xindaoapp.happypet.api.AddClient;
import com.xindaoapp.happypet.api.Address;
import com.xindaoapp.happypet.api.ConstantsValue;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.UploadInfo;
import com.xindaoapp.happypet.bean.UserInfo;
import com.xindaoapp.happypet.utils.BitmapHelp;
import com.xindaoapp.happypet.utils.CommonParameter;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.MoccaPreferences;
import com.xindaoapp.happypet.utils.ProgressHUD;
import com.xindaoapp.happypet.view.CircleImageView;

public class UserInfoActivity extends UMBaseActivity implements OnClickListener {
    private static final int CAMERA = 0;
    private static final int ALBUM = 1;
    private static final int PHOTORESOULT = 2;
    private static final String IMAGE_UNSPECIFIED = "image/*";
    private static final int crop = 64;
    protected static final int SUCCESS = 10;
    protected static final int FAIL = 20;
    @ViewInject(R.id.tittle_common_cancel)
    private ImageView tittle_common_cancel;
    @ViewInject(R.id.tittle_common_content)
    private TextView tittle_common_content;

    @ViewInject(R.id.userinfo_touxiang_img)
    private CircleImageView userinfo_touxiang_img;
    @ViewInject(R.id.userinfo_username)
    private TextView userinfo_username;
    @ViewInject(R.id.userinfo_mail)
    private TextView userinfo_mail;
    @ViewInject(R.id.userinfo_niuniu)
    private TextView userinfo_niuniu;
    @ViewInject(R.id.userinfo_logout)
    private Button userinfo_logout;
    @ViewInject(R.id.userinfo_touxiang)
    private RelativeLayout userinfo_touxiang;

    @ViewInject(R.id.pic_edit)
    private ImageView pic_edit;

    @ViewInject(R.id.userinfo)
    private RelativeLayout userinfo;
    @ViewInject(R.id.picinfo)
    private RelativeLayout picinfo;

    @ViewInject(R.id.title_left)
    private ImageButton title_left;
    @ViewInject(R.id.title_right)
    private ImageButton title_right;


    @ViewInject(R.id.name)
    private TextView name;


    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SUCCESS:
                    Toast.makeText(getBaseContext(), "上传成功", Toast.LENGTH_SHORT).show();
                    userinfo.setVisibility(View.VISIBLE);
                    picinfo.setVisibility(View.GONE);
                    ConstantsValue.ISUPLOADSUCCESS = true;
                    Editor edit = sp.edit();
                    edit.putString("uid", UserState.getUser().uid);
                    edit.commit();
                    initUserInfo();
                    break;
                case FAIL:
                    Toast.makeText(getBaseContext(), "上传失败", Toast.LENGTH_SHORT).show();
                    break;
                case 30:
                    userinfo_niuniu.setText(niuniu);
                    break;

                default:
                    break;
            }
        };
    };
    private SharedPreferences sp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_userinfo);
        sp = getSharedPreferences("userconfig", MODE_PRIVATE);

        ViewUtils.inject(this);
        userinfo.setVisibility(View.VISIBLE);
        picinfo.setVisibility(View.GONE);
        initClick();
    }

    private void initClick() {
        tittle_common_content.setText("详细资料");
        tittle_common_cancel.setOnClickListener(this);
        userinfo_logout.setOnClickListener(this);
        userinfo_touxiang.setOnClickListener(this);
        title_left.setOnClickListener(this);
        title_right.setOnClickListener(this);
    }

    private LinearLayout pic_selector_camera;
    private LinearLayout pic_selector_album;
    // 图片文件夹的地址
    private File filepath;
    // 图片的地址
    private File picPath;
    private AlertDialog dialog;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tittle_common_cancel:
                finish();
                break;
            case R.id.userinfo_logout:
                // ConstantsValue.user = null;
                // ConstantsValue.uid = "";
                // ConstantsValue.isLogin = false;
                // ConstantsValue.ISUPLOADSUCCESS=false;
                Intent intent = new Intent(ConstantsValue.LOGOUT_SUCCESS);
                UserInfoActivity.this.sendBroadcast(intent);
                Toast.makeText(getApplicationContext(), "退出登录成功", Toast.LENGTH_SHORT).show();
                JPushInterface.stopPush(getBaseContext());
                // if (HappyPetApplication.get().getQqAuth().isSessionValid()) {
                HappyPetApplication.get().getQqAuth().logout(getBaseContext());
                // HappyPetApplication.get().getTencent().logout(getBaseContext());
                CommonUtil.logoutQQ(UserInfoActivity.this);
                // }
                XDHttpClient.client.getCookie().clear();
                AddClient.getClient().getCookie().clear();
                ConstantsValue.cookieStore = null;
                MoccaPreferences.CookieData.put("");
                // HappyPetApplication.get().setQqAuth();
                finish();
                break;
            case R.id.userinfo_touxiang:

                showDialog();
                break;
            case R.id.pic_selector_camera:
                Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                initFilePath();
                camera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(picPath));
                camera.putExtra("outputFormat", "JPEG");
                startActivityForResult(camera, CAMERA);
                break;
            case R.id.pic_selector_album:
                Intent album = new Intent("android.intent.action.PICK");
                album.setDataAndType(MediaStore.Images.Media.INTERNAL_CONTENT_URI, "image/*");
                initFilePath();
                album.putExtra("output", Uri.fromFile(picPath));

                album.putExtra("crop", "true");

                album.putExtra("aspectX", 1); // 裁剪框比例

                album.putExtra("aspectY", 1);

                album.putExtra("outputX", crop);// 输出图片大小

                album.putExtra("outputY", crop);
                album.putExtra("return-data", true);
                startActivityForResult(album, ALBUM);
                // Intent picture = new
                // Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                // startActivityForResult(picture, ALBUM);
                break;
            case R.id.title_left:
                userinfo.setVisibility(View.VISIBLE);
                picinfo.setVisibility(View.GONE);
                // finish();
                break;
            case R.id.title_right:
                uploadPIC();
                break;
            default:
                break;
        }
    }

    private void showDialog() {
        AlertDialog.Builder builder = new Builder(this);
        View view = View.inflate(UserInfoActivity.this, R.layout.pic_selector, null);
        pic_selector_camera = (LinearLayout) view.findViewById(R.id.pic_selector_camera);
        pic_selector_album = (LinearLayout) view.findViewById(R.id.pic_selector_album);

        pic_selector_camera.setOnClickListener(UserInfoActivity.this);
        pic_selector_album.setOnClickListener(UserInfoActivity.this);

        dialog = builder.create();
        dialog.setOnCancelListener(new OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                dialog.dismiss();
            }
        });
        dialog.setView(view);
        dialog.show();
    }

    private void uploadPIC() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("uid", UserState.getUserUid());
        params.addBodyParameter("img", new File(filepath, "userpic.jpg"));
        HttpUtils utils = new HttpUtils();
        if (ConstantsValue.cookieStore != null) {
            utils.configCookieStore(ConstantsValue.cookieStore);
        }
        final ProgressHUD progressHUD =
                ProgressHUD.show(UserInfoActivity.this, "正在加载...", true, true, null);
        utils.send(HttpMethod.POST, Address.CHANGEPIC, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                try {
                    if (null != progressHUD && progressHUD.isShowing()) {
                        progressHUD.dismiss();
                    }
                    UploadInfo picinfo = JSON.parseObject(responseInfo.result, UploadInfo.class);
                    if (picinfo.getResult().equals("0")) {
                        handler.sendEmptyMessage(SUCCESS);
                    }
                    if (picinfo.getResult().equals("5")) {
                        handler.sendEmptyMessage(FAIL);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                if (null != progressHUD && progressHUD.isShowing()) {
                    progressHUD.dismiss();
                }
                Toast.makeText(getApplicationContext(), "上传失败", Toast.LENGTH_SHORT).show();
            }
        });

    }

    private void initFilePath() {
        filepath = new File(Environment.getExternalStorageDirectory(), "temp");
        if (!filepath.exists()) {
            filepath.mkdirs();
        }
        picPath = new File(filepath, "temp.jpg");
        ConstantsValue.uri = Uri.fromFile(picPath);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAMERA) {
            if (ConstantsValue.uri == null) {
                Toast.makeText(this, "没有选取图片", 0).show();
                return;
            }
            userinfo.setVisibility(View.GONE);
            picinfo.setVisibility(View.VISIBLE);
            startPhotoZoom(ConstantsValue.uri);

        }

        // 读取相册缩放图片
        if (requestCode == ALBUM) {
            if (!picPath.exists()) {
                Toast.makeText(this, "没有选取图片", 0).show();
                return;
            }

            userinfo.setVisibility(View.GONE);
            picinfo.setVisibility(View.VISIBLE);
            startPhotoZoom(Uri.fromFile(picPath));
        }
        if (requestCode == PHOTORESOULT) {
            if (data == null) {
                Toast.makeText(this, "没有选取图片", 0).show();
                return;
            }
            Bundle extras = data.getExtras();
            if (extras != null) {
                Bitmap photo = extras.getParcelable("data");
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                photo.compress(Bitmap.CompressFormat.PNG, 75, stream);// (0 -
                                                                      // 100)压缩文件
                pic_edit.setImageBitmap(photo);
                try {
                    FileOutputStream out = new FileOutputStream(new File(filepath, "userpic.jpg"));
                    photo.compress(Bitmap.CompressFormat.JPEG, 75, out);
                    out.flush();
                    out.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onResume() {
        initUserInfo();
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        super.onResume();
    }

    private void initUserInfo() {
        // ImageLoader.getInstance().clearDiscCache();
        // ImageLoader.getInstance().clearMemoryCache();

        userinfo_niuniu.setText(UserState.getUser().niuniu);
        initUserInfo(UserState.getUser().uid);
        userinfo_username.setText(UserState.getUser().username);
        userinfo_mail.setText(UserState.getUser().email);
        name.setText(UserState.getUser().username);
        if (ConstantsValue.ISUPLOADSUCCESS) {
            if (!TextUtils.isEmpty(sp.getString("uid", ""))) {
                File filepath = new File(Environment.getExternalStorageDirectory(), "temp");
                File file = new File(filepath, "userpic.jpg");
                Bitmap decodeFile = BitmapFactory.decodeFile(file.getAbsolutePath());
                userinfo_touxiang_img.setImageBitmap(decodeFile);
            }
        } else {
            if (CommonParameter.isLoadImg) {
                BitmapDisplayConfig config = new BitmapDisplayConfig();
                config.setLoadingDrawable(getResources().getDrawable(R.drawable.person_loading));
                config.setLoadFailedDrawable(getResources().getDrawable(R.drawable.person_loading));
                BitmapHelp.getBitmapUtils(getApplicationContext()).display(userinfo_touxiang_img,
                        UserState.getUser().userface, config);
            } else {
                userinfo_touxiang_img.setImageResource(R.drawable.person_loading);
            }
        }

    }

    private String niuniu = "";

    private void initUserInfo(String uid2) {
        com.loopj.android.http.RequestParams params = new com.loopj.android.http.RequestParams();
        params.put("uid", uid2);
        final ProgressHUD progressHUD = ProgressHUD.show(this, "正在加载...", true, true, null);
        AddClient.get(Address.GETUSERINFOBYUID, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, String content) {
                try {
                    if (null != progressHUD && progressHUD.isShowing()) {
                        progressHUD.dismiss();
                    }
                    UserInfo parse = JSON.parseObject(content, UserInfo.class);
                    if (parse.getResult().equals("0")) {
                        niuniu = parse.userinfo.niuniu;
                        handler.sendEmptyMessage(30);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                super.onSuccess(statusCode, content);
            }

            @Override
            public void onFailure(Throwable error, String content) {
                if (null != progressHUD && progressHUD.isShowing()) {
                    progressHUD.dismiss();
                }
                super.onFailure(error, content);
            }
        });
    }

    public static Bitmap getHttpBitmap(String url) {
        URL myFileUrl = null;
        Bitmap bitmap = null;
        try {
            myFileUrl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
            conn.setConnectTimeout(0);
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", crop);
        intent.putExtra("outputY", crop);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, PHOTORESOULT);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

}
